<template>
  <div class="container">
    <div class="mainContainer">
      <el-col class="departmentMenu" id="departmentMenu">
        <div class="titleBoxCon" id="departmentMenuTitleBox">
          <div style="float: right; margin-top: 2px">
            <el-button
              type="primary"
              class="commonBut saveBtn funComBut"
              icon="icon iconfont icontianjia"
              @click="handleAdd"
              v-show="isShowAdd"
            >
              <span class="opetareText">新增部门</span>
            </el-button>
          </div>
          <div class="title" id="departmentMenuTitle">部门列表</div>
        </div>
        <el-tree
          :data="treeData"
          empty-text="尚未创建部门"
          node-key="id"
          :props="defaultProps"
          default-expand-all
          @node-click="handleNodeClick"
          ref="tree"
          :highlight-current="true"
          style="background: #e7ecf3; padding: 15px"
        ></el-tree>
      </el-col>
      <el-col
        class="departmentModify"
        id="departmentModify"
        v-show="action !== 'show'"
      >
        <div class="titleBoxCon">
          <el-button
            class="commonBut saveBtn funComBut"
            style="float: right; margin-top: 6px"
            @click="handleDelete"
            v-if="action === 'modify' && isShowDel"
            >删除部门</el-button
          >
          <div class="title">{{ action === 'add' ? '新增部门' : dname }}</div>
        </div>
        <el-form
          :model="formData"
          :rules="formRules"
          ref="formData"
          label-width="100px"
          class="form"
        >
          <el-form-item label="上级部门" prop="parentId">
            <!-- <div v-if="action === 'add'">{{formData.dpName}}</div> -->
            <el-cascader
              v-model="parentId"
              :props="defaultProps"
              :options="orglist"
              @change="handleChange"
              clearable
              filterable
            ></el-cascader>
          </el-form-item>
          <el-form-item prop="name" label="部门名称">
            <el-input
              v-model.trim="formData.name"
              placeholder="请输入部门名称"
              class="input"
              maxlength="20"
            ></el-input>
          </el-form-item>
          <el-form-item prop="remark" label="部门简介">
            <el-input
              type="textarea"
              v-model.trim="formData.remark"
              autocomplete="off"
              placeholder="请输入部门简介"
              maxlength="200"
              show-word-limit
              rows="4"
              class="input"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item prop="sortCode" label="部门排序">
            <el-input
              v-model.trim="formData.sortCode"
              placeholder="请输入部门排序"
              class="input"
              style="width: 26%; margin-right: 10px"
              maxlength="10"
            ></el-input
            >（值越大排序越靠前）
          </el-form-item>
          <el-form-item>
            <el-button
              class="commonBut saveBtn"
              type="primary"
              @click="handleSave"
              :loading="isSaveLoading"
              v-if="isShowSave"
              >保存</el-button
            >
            <el-button class="commonBut" v-else type="info" plain disabled
              >保存</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
      <div class="emptyBox" v-show="action === 'show'">
        <div class="departmentModify empty">请先选择部门，再进行操作</div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'departmentManager',
  components: {},
  data() {
    var checkArea = (rule, value, callback) => {
      var that = this
      if (!that.parentId || that.parentId.length < 1) {
        return callback(new Error('上级部门不能为空'))
      } else {
        callback()
      }
    }
    var validateSortCode = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('请输入部门排序'))
      } else if (!/(^[1-9]\d*$)/.test(value)) {
        callback(new Error('请输入正整数'))
      } else {
        callback()
      }
    }
    return {
      treeData: [],
      defaultProps: {
        children: 'child',
        label: 'name',
        value: 'id',
        checkStrictly: true,
      },
      currentChildLen: 0, //当前节点儿子长度
      currentId: '', //当前节点id
      isSaveLoading: false,
      formData: {
        parentId: 0,
        name: '',
        remark: '',
        sortCode: '',
      },
      dname: '',
      idMap: {},
      formRules: {
        parentId: [
          {
            required: true,
            validator: checkArea,
            // message: "所在部门不能为空",
            trigger: 'change',
          },
        ],
        name: [
          {
            required: true,
            message: '请填写部门名称',
            trigger: 'blur',
          },
        ],
        sortCode: [
          {
            required: true,
            validator: validateSortCode,
            trigger: 'blur',
          },
        ],
      },
      action: 'show',
      did: 5,
      orglist: [],
      parentId: '',
      refreshDpList: true,
      isShowDel: '',
      isShowSave: '',
      isShowAdd: '',
    }
  },
  watch: {
    action(val) {
      if (val !== 'show') {
        this.$nextTick(() => {
          $('.departmentModify')[0].style.height = '100%'
        })
      } else {
        this.$nextTick(() => {
          $('.departmentModify')[0].style.height = ''
        })
      }
    },
  },
  created() {
    this.getTreeData('first')
    this.isShowAdd =
      this.$store.state.buttonLimitsArr.indexOf('depart:add') > -1
    this.isShowSave =
      (this.$store.state.buttonLimitsArr.indexOf('depart:add') > -1 &&
        this.action == 'add') ||
      this.$store.state.buttonLimitsArr.indexOf('depart:update') > -1
    this.isShowDel =
      this.$store.state.buttonLimitsArr.indexOf('depart:delete') > -1
  },
  mounted() {
    $(document).mousedown((event) => {
      if (Object.keys($('#departmentMenu')).length > 0) {
        if (
          $('#departmentMenuTitleBox')[0] === event.target ||
          $('#departmentMenuTitle')[0] === event.target ||
          $('#departmentMenu')[0] === event.target
        ) {
          if (this.$refs.tree.getCurrentKey()) {
            this.$refs.tree.setCurrentKey(null)
            this.action = 'show'
          }
        }
      }
    })
  },
  methods: {
    handleChange() {
      this.formData.parentId = this.parentId[this.parentId.length - 1]
    },
    handleNodeClick(data, node) {
      this.isShowSave =
        this.$store.state.buttonLimitsArr.indexOf('depart:update') > -1 &&
        this.action == 'modify'
      this.$refs['formData'].resetFields()
      this.currentChildLen = data.child.length
      this.currentId = data.id
      this.$nextTick(() => {
        this.getRoleInfo(this.currentId)
        this.getOrglist(this.currentId)
      })
      this.action = 'modify'
    },
    getRoleInfo(roleId) {
      this.axios({
        method: 'post',
        url: 'api-m/dept/detail',
        data: {
          id: roleId,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            var data = response.data.result
            this.parentId = data.parentId
            this.formData.parentId = data.parentId
            this.formData.name = data.name
            this.dname = data.name
            this.formData.remark = data.remark
            this.formData.sortCode = data.sortCode
          } else {
            this.$message({
              type: 'error',
              message: res.data.errorMsg,
            })
          }
        })
        .catch((error) => {
          this.$message.error('角色数据获取失败')
        })
    },
    getOrglist(currentId) {
      this.axios({
        method: 'post',
        url: 'api-m/dept/combobox',
        data: {
          id: currentId,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.orglist = response.data.result
              //1.未选中左侧部门，点击新增，上级部门默认“部门列表”
              //2.选中左侧部门后新增，建议上级部门默认带入选中部门
              if (!this.currentId && this.action == 'add') {
                this.parentId = '0'
              } else if (this.currentId && this.action == 'add') {
                this.parentId = this.currentId
                this.formData.parentId = this.currentId
              }
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    handleAdd() {
      this.action = 'add'
      this.isShowSave =
        this.$store.state.buttonLimitsArr.indexOf('depart:add') > -1 &&
        this.action == 'add'
      this.$refs['formData'].resetFields()
      // if(this.currentId) {
      //   this.getOrglist(this.currentId);
      // } else {
      //   this.getOrglist();
      // }
      this.getOrglist()
    },
    saveDept() {
      this.axios({
        method: 'post',
        url: 'api-m/dept/add',
        data: this.formData,
      })
        .then((resp) => {
          if (!resp.data.hasError) {
            this.isSaveLoading = false
            this.currentId = resp.data.result
            this.$message({
              message: '保存成功',
              type: 'success',
            })

            this.$nextTick(() => {
              this.getTreeData()
              this.action = 'modify'
              this.isShowSave =
                this.$store.state.buttonLimitsArr.indexOf('depart:update') >
                  -1 && this.action == 'modify'
              this.dname = this.formData.name
              setTimeout(() => {
                this.$refs.tree.setCurrentKey(this.currentId)
              }, 500)
            })
          } else {
            this.$message({
              type: 'error',
              message: resp.data.errorMsg,
            })
            this.isSaveLoading = false
          }
        })
        .catch((error) => {
          this.isSaveLoading = false
        })
    },
    updateDept() {
      this.formData.id = this.currentId
      this.axios({
        method: 'post',
        url: 'api-m/dept/edit',
        data: this.formData,
      })
        .then((resp) => {
          if (!resp.data.hasError) {
            this.isSaveLoading = false
            this.$message({
              message: '修改成功',
              type: 'success',
            })
            this.dname = this.formData.name
            this.$nextTick(() => {
              this.getTreeData()
              setTimeout(() => {
                this.$refs.tree.setCurrentKey(this.currentId)
              }, 500)
            })
          } else {
            this.$message({
              type: 'error',
              message: resp.data.errorMsg,
            })
            this.isSaveLoading = false
          }
        })
        .catch((error) => {
          this.isSaveLoading = false
        })
    },
    deleteDept() {
      this.axios({
        method: 'post',
        url: 'api-m/dept/delete',
        data: {
          id: this.currentId ? this.currentId : this.treeData[0].id,
        },
      })
        .then((resp) => {
          if (!resp.data.hasError) {
            this.$message({
              message: '删除成功',
              type: 'success',
            })
            this.$nextTick(() => {
              this.getTreeData()
              this.action = 'show'
            })
            // this.orglist = response.data.result;
          } else {
            this.$message({
              type: 'error',
              message: resp.data.errorMsg,
            })
          }
        })
        .catch((error) => {})
    },
    getTreeData(params) {
      this.axios({
        method: 'post',
        url: 'api-m/dept/tree',
      })
        .then((resp) => {
          this.treeData = resp.data.result
          //部门进页面默认第一个
          if (params) {
            this.getRoleInfo(this.treeData[0].id)
            this.getOrglist(this.treeData[0].id)
            // this.action = "show";
            this.action = 'modify'
            setTimeout(() => {
              this.$refs.tree.setCurrentKey(this.treeData[0].id)
            }, 500)
          }
        })
        .catch((error) => {})
    },
    sortTree(data) {
      data.sort((a, b) => {
        return a.sortCode - b.sortCode
      })
      data.map((v) => {
        if (v.children) {
          this.sortTree(v.children)
        }
      })
    },
    removeItem(array, i) {
      var a = array.slice(0)
      a.splice(i, 1)
      return a
    },
    constructTree(res, obj, parentId, children) {
      if (res.length === 0) {
        return
      }
      res.map((v, i) => {
        if (v.parentId === parentId) {
          children.push(v)
          v.children = []
          this.constructTree(this.removeItem(res, i), v, v.did, v.children)
        }
      })
      if (obj.children.length === 0) {
        delete obj.children
      }
    },
    handleDelete() {
      this.$confirm('确认删除部门【' + this.dname + '】？', '删除部门', {
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning',
      })
        .then(() => {
          // var node = this.$refs.tree.getNode(this.$refs.tree.getCurrentNode());
          if (this.currentChildLen === 0) {
            this.deleteDept()
          } else {
            this.$confirm(
              '部门【' + this.dname + '】有下级部门或部门成员，不能直接删除',
              '删除部门',
              {
                cancelButtonClass: 'btn-custom-cancel',
                type: 'warning',
              }
            )
          }
        })
        .catch((error) => {})
    },
    handleSave() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.isSaveLoading = true
          if (this.action === 'add') {
            this.saveDept()
          } else if (this.action === 'modify') {
            this.updateDept()
          }
        } else {
          return false
        }
      })
    },
  },
}
</script>

<style scoped lang="less">
.custom-tree-node {
  width: 90%;
  .dname {
    width: 93%;
    display: inline-block;
    vertical-align: middle;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
  }
}
/deep/ .el-tree-node__label {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
/deep/ .el-tree-node__content {
  height: 30px;
  padding-left: -200px;
}
/deep/ .custom-tree-node {
  width: 100% !important;
  float: left !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  white-space: normal !important;
}

/deep/.el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  background-color: #ebf0f5;
}
.mainContainer {
  // position: absolute;
  // top: 24px;
  // left: 0px;
  // right: 24px;
  // bottom: 0px;
  // background: #fff;
  // overflow-y: auto;
  height: 100%;
  .titleBoxCon {
    line-height: 50px;
    height: 50px;
    border-bottom: 0.5px solid #e3e7e9;
    margin: 0 24px;
    .title {
      color: #333;
      font: bold 18px SourceHanSansCN-Medium;
      line-height: 31px;
      padding-top: 10px;
    }
  }
  .divider {
    margin-top: 15px;
  }
  .departmentMenu {
    width: 30%;
    height: 100%;
    // padding: 24px;
    background: #e7ecf3;
  }
  .departmentModify {
    width: 70%;
    padding: 0;
    .form {
      margin-left: 5%;
      margin-top: 5%;
      .el-form-item {
        margin-bottom: 24px;
      }
      .input {
        width: 60%;
        font: 14px SourceHanSansCN-Medium;
      }
    }
  }
  .emptyBox {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    width: 1920px;
    // height: 600px;
    padding-top: 250px;
    .empty {
      color: #999;
      margin: auto;
    }
  }
}
</style>
